package com.itheima.tanhua.dubbo.mongo.api.impl;

import cn.hutool.core.collection.CollUtil;
import com.itheima.tanhua.api.CommentApi;
import com.itheima.tanhua.api.VideoApi;
import com.itheima.tanhua.dubbo.mongo.utils.IdWorker;
import com.itheima.tanhua.mongo.Comment;
import com.itheima.tanhua.mongo.Movement;
import com.itheima.tanhua.mongo.Video;
import com.itheima.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

/**
 * @author Lff
 * @date 2022/4/3
 */
@DubboService
public class VideoApiImpl implements VideoApi {
    @Autowired
    private MongoTemplate mongo;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private CommentApi commentApi;

    /**
     * 保存一条记录
     *
     * @param video
     * @return
     */
    @Override
    public String save(Video video) {
        //填充id
        ObjectId objectId = ObjectId.get();
        video.setId(objectId);
        //填充vid
        Long vid = idWorker.getNextId("video");
        video.setVid(vid);
        //保存
        mongo.save(video);
        return objectId.toHexString();
    }

    /**
     * 根据vid查询视频集合
     * <p>
     * 如果不存在vid则按照时间默认查询
     *
     * @param vidList
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Video> getRecommendVideoList(List<Long> vidList, Integer page, Integer pagesize) {
        if (CollUtil.isEmpty(vidList)) {
            //为null
            Query created = new Query()
                    .skip((page - 1) * pagesize) //开始序列
                    .limit(pagesize)//页尺寸
                    .with(Sort.by(Sort.Order.desc("created"))); //排序规则
            //返回数据
            return mongo.find(created, Video.class);
        }
        Query query = new Query(Criteria.where("vid").in(vidList));
        return mongo.find(query, Video.class);
    }

    /**
     * 保存数据评论。点赞，手藏等数据，并更新video的数据
     *
     * @param c
     * @return
     */
    @Override
    public Integer publishAll(Comment c) {
        Video v = mongo.findOne(Query.query(Criteria.where("id").is(c.getPublishId())), Video.class);
        c.setPublishUserId(v.getUserId());
        //保存评论
        mongo.save(c);
        //修改视频的数据
        Update up = new Update();
        Query id = Query.query(Criteria.where("id").is(v.getId()));
        FindAndModifyOptions ops = new FindAndModifyOptions();
        ops.returnNew(true);
        if (c.getCommentType() == 5) {
            up.inc("likeCount");
        } else if (c.getCommentType() == 6) {
            up.inc("commentCount");
        } else if (c.getCommentType() == 7) {
            up.inc("loveCount");
        }
        Video video = mongo.findAndModify(id, up, ops, Video.class);
        return video.staticCount(c.getCommentType());
    }

    /**
     * @param comment
     * @return
     */
    @Override
    public Integer removeAll(Comment comment) {
        //删除对应comments表数据
        Criteria remove = Criteria.where("publishId").is(comment.getPublishId())
                .and("userId").is(comment.getUserId())
                .and("commentType").is(comment.getCommentType());
        Query query = Query.query(remove);
        mongo.remove(query, Comment.class);
        //数据自减
        //修改视频的数据
        Update up = new Update();
        Query id = Query.query(Criteria.where("id").is(comment.getPublishId()));
        FindAndModifyOptions ops = new FindAndModifyOptions();
        ops.returnNew(true);
        if (comment.getCommentType() == 4) {
            up.inc("likeCount", -1);
        } else if (comment.getCommentType() == 5) {
            up.inc("commentCount", -1);
        } else if (comment.getCommentType() == 6) {
            up.inc("loveCount", -1);
        }
        Video video = mongo.findAndModify(id, up, ops, Video.class);
        return video.staticCount(comment.getCommentType());
    }

    /**
     * @param page      页码
     * @param pagesize  页尺寸
     * @param uid       用户id
     * @param sortProp  排序字段
     * @param sortOrder 排序规则
     * @return
     */
    @Override
    public PageResult findUserVideos(Integer page, Integer pagesize, Long uid, String sortProp, String sortOrder) {
        Query q = new Query();
        if (uid != null) {
            q.addCriteria(Criteria.where("userId").is(uid));
        }
        //统计数量
        long count = mongo.count(q, Video.class);
        q.skip((page - 1) * pagesize)
                .limit(pagesize);
        if (sortProp != null) {
            if (sortProp != null && sortOrder.equals("ascending")) {
                q.with(Sort.by(Sort.Order.asc(sortProp)));
            } else {
                q.with(Sort.by(Sort.Order.desc(sortProp)));
            }
        }
        List<Video> videos = mongo.find(q, Video.class);
        if (CollUtil.isEmpty(videos)) {
            return new PageResult();
        }

        PageResult pageResult = new PageResult(page, pagesize, count, videos);
        //返回数据
        return pageResult;
    }


}
